﻿using System;
using System.Collections.Generic;
using System.Linq;
using EncuentraloSilverlight.Web.Models;
using System.Data.Linq;



namespace EncuentraloSilverlight.Models
{
    public class UserRepository
    {
        private EncuentraloDataBaseModelDataContext db;

        public UserRepository()
        {
            db = new EncuentraloDataBaseModelDataContext();
            DataLoadOptions options = new DataLoadOptions();
            options.LoadWith<User>(k => k.Addresses);
            options.LoadWith<User>(k => k.Searches);
            db.LoadOptions = options;
        }

        //Query Methods

        public IQueryable<User> FindAllUsers()
        {
            return db.Users;
        }

        public IQueryable<User> FindUsersFromUsername(string parameter)
        {
            try
            {
                var temp = db.Users.Where(k => k.Name.Equals(parameter));
                return temp;
            }
            catch (Exception e)
            {
                return null;
            }
            
        }

        //Insert & Delete Methods

        public void AddUser(User user)
        {
            db.Users.InsertOnSubmit(user);
            Save();
        }

        public void DeleteUser(User user)
        {
            db.Addresses.DeleteAllOnSubmit(user.Addresses);
            db.Searches.DeleteAllOnSubmit(user.Searches);
            db.Users.DeleteOnSubmit(user);
            Save();
        }
        public void EditUserName(User user, string name)
        {
            db.Users.FirstOrDefault( k=> k==user).Name=name;           
            Save();
        }
        public void EditUserAddress(User user, Address address)
        {
            db.Users.FirstOrDefault(k => k == user).Addresses[0] = address;
            Save();
        }

        public void AddSearchfromUser(User user, Search search)
        {
            db.Users.FirstOrDefault(u => u.Name.Equals(user.Name)).Searches.Add(search);

            var searches = db.Users.FirstOrDefault(u => u.Name.Equals(user.Name)).Searches.OrderByDescending(u => u.Date);

            while (db.Users.FirstOrDefault(u => u.Name.Equals(user.Name)).Searches.Count > 20)
            {
                for(int i=20; i<db.Users.FirstOrDefault(u => u.Name.Equals(user.Name)).Searches.Count; i++)
                {
                    db.Users.FirstOrDefault(u => u.Name.Equals(user.Name)).Searches.Remove(searches.ElementAt(i));
                }
            }
            Save();
        }


        // Persistence
        private void Save()
        {
            db.SubmitChanges();
        }

    }
}